package controller

import (
	"encoding/json"
	"net/http"
	"osiris/dto"
	"osiris/logger"
	"osiris/ocrypto/ecdsa"

	"github.com/gin-gonic/gin"
)

// TestController 仅供测试使用的业务逻辑
type TestController struct{}

// TxDataSignHandler 为交易计算Hash并签名（需在TxData的TxDatamap中提供privKey）
//
//	@receiver controller
//	@param context
func (controller TestController) TxDataSignHandler(context *gin.Context) {
	var txData dto.TxData

	if err1 := context.BindJSON(&txData); err1 != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err1.Error()})
		return
	}

	if txData.TxDataMap[dto.KEY_PRIVKEY] == "" {
		context.JSON(http.StatusBadRequest, gin.H{"error": "no privKey provided in the txDatamap!"})
		return
	}

	//私钥字符串转*ecdsa.PrivateKey
	privKey, err2 := ecdsa.StrToECDSAPrivKey(txData.TxDataMap[dto.KEY_PRIVKEY])
	if err2 != nil {
		logger.Error(map[string]interface{}{"[dto] [Hash And Sign TxData] str to privKey": err2})
		context.JSON(http.StatusInternalServerError, gin.H{
			"Ivalid PrivKey": err2.Error(),
		})
		return
	}
	txData.HashAndSign(privKey, false)

	bytes, err3 := json.Marshal(txData)
	if err3 != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"TxData Serialization": err3.Error(),
		})
		return
	}
	context.JSON(http.StatusOK, string(bytes))
}
